package com.zhentao.utils;

import com.zhentao.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * JWT工具类
 * 用于生成和解析JWT令牌
 */
public class JwtUtil {
    
    // JWT密钥 - 应该从配置文件中读取，这里为了简化直接硬编码
    private static final SecretKey JWT_KEY = Keys.hmacShaKeyFor(
            "OceanBridge-SecretKey-Use-At-Least-256-bit-Length-For-HS256".getBytes(StandardCharsets.UTF_8));
    
    /**
     * 为用户生成JWT令牌
     * 
     * @param user 用户对象
     * @param ttlMs 令牌有效期（毫秒）
     * @return JWT令牌字符串
     */
    public static String generateJwt(User user, long ttlMs) {
        long now = System.currentTimeMillis();
        Date nowDate = new Date(now);
        Date expireDate = new Date(now + ttlMs);
        
        return Jwts.builder()
                .setSubject(String.valueOf(user.getId()))
                .claim("username", user.getUsername())
                .claim("email", user.getEmail())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(JWT_KEY, SignatureAlgorithm.HS256)
                .compact();
    }
}